package com.wct.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.wct.spzx.manager.service.ValidateCodeService;
import com.wct.spzx.model.vo.system.ValidateCodeVo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode() {
        // 1通过工具生成图片验证码
        // hutool--int width, int height, int codeCount, int circleCount
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150,50,4,2);
        // 4位验证码值
        String codeValue = circleCaptcha.getCode();
        // 图片验证码，base64编码
        String imageBase64 = circleCaptcha.getImageBase64();
        // 2 把验证码存储到redis中
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(key, codeValue, 2, TimeUnit.MINUTES);

        // 3返回对象
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(key);
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);
        return validateCodeVo;
    }
}
